<template>
	<!-- 返修领料单 -->
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="85px"
			class="queryForms">
			<el-form-item label="返修任务单" prop="repairNumber">
				<el-input v-model="queryParams.repairNumber" placeholder="请输入返修任务单" clearable
					@keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="产品名称" prop="productName">
				<el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable
					@keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="产品型号" prop="productModel">
				<el-input v-model="queryParams.productModel" placeholder="请输入产品型号" clearable
					@keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="产品编号" prop="productNumber">
				<el-input v-model="queryParams.productNumber" placeholder="请输入产品编号" clearable
					@keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="状态" prop="approvalRequisitionStatus">
				<el-select v-model="queryParams.approvalRequisitionStatus">
					<el-option v-for="item in approvalRequisitionStatusList" :key="item.id" :label="item.name"
						:value="item.id"></el-option>
				</el-select>
				<!-- <el-input v-model="queryParams.approvalRequisitionStatus" placeholder="请输入产品编号" clearable @keyup.enter.native="handleQuery" maxlength="20" show-word-limit  /> -->
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAddReceive()"
					v-hasPermi="['taskFilling:repair:addReceive']">生成领料单</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="primary" icon="el-icon-circle-check" size="mini" @click="handleSubmits"
					v-hasPermi="['taskFilling:repair:submit']">提交</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="primary" icon="el-icon-s-order" size="mini" @click="handleApprove"
					v-hasPermi="['taskFilling:repair:approve']">审批</el-button>
			</el-col>
			<CreateForm :ids="ids" formtype="t_createChangeData" />
			<right-toolbar @changeTableData="changeTableData" menuNames="repair78" :showSearch.sync="showSearch"
				@queryTable="handleQuery" :columns.sync="columns" perm="taskFilling:repair:index"></right-toolbar>
		</el-row>
		<div :class="sidebar.opened && eleTabTop <= 85 ? 'eleTab' : !sidebar.opened && eleTabTop <= 85 ? 'eleTabs' : ''"
			class="informationTab" ref="eleTab">
			<el-table :key="treetablekey" @expand-change="handleExpandChange" :row-class-name="row_class_name"
				@mousedown.native="mousedownTable" @row-click="row_click" @cell-mouse-enter="cell_mouse_enter"
				@cell-mouse-leave="cell_mouse_leave" @mouseup.native="mouseupTable" @mouseleave.native="mouseupTable"
				v-loading="loading" :data="RepairList" @selection-change="handleSelectionChange" row-key="id" lazy
				:load="loadListDes" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
				ref="treetableref" border height="100%">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column label="序号" align="center" type="index" width="55">
					<template slot-scope="scope">
						<div>{{ scope.row.sort }}</div>
					</template>
				</el-table-column>
				<el-table-column label="返修任务单" prop="repairNumber" min-width="250" :show-overflow-tooltip="true"
					v-if="columns[0].visible" />
				<el-table-column label="产品名称" prop="productName" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[1].visible" />
				<el-table-column label="产品型号" prop="productModel" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[2].visible" />
				<el-table-column label="产品编号" prop="productNumber" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[3].visible" />
				<el-table-column label="工艺流程" prop="productName" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[4].visible" />
				<el-table-column label="审批状态" prop="approvalStateName" min-width="150" align="center"
					:show-overflow-tooltip="true" v-if="columns[5].visible">
					<template slot-scope="scope">
						<el-tag type="info" v-if="scope.row.approvalStatus === '0'" class="disableClick">未提交</el-tag>
						<el-tag v-if="scope.row.approvalStatus === '1'" @click="showApproveList(scope.row)"
							class="clickable">审批中</el-tag>
						<el-tag type="success" v-if="scope.row.approvalStatus === '2'"
							@click="showApproveList(scope.row)" class="clickable">已通过</el-tag>
						<el-tag type="danger" v-if="scope.row.approvalStatus === '3'"
							@click="showApproveList(scope.row)" class="clickable">未通过</el-tag>
					</template>
				</el-table-column>

				<el-table-column label="生成标志" prop="generateFlag" min-width="150" align="center"
					:show-overflow-tooltip="true" v-if="columns[6].visible">
					<template slot-scope="scope">
						<div v-if="scope.row.generateFlag == 0">未生成</div>
						<div v-if="scope.row.generateFlag == 1">已生成</div>
					</template>
				</el-table-column>
				<el-table-column label="操作" class-name="small-padding fixed-width" width="220px" fixed="right">
					<template slot-scope="scope">
						<section v-if="scope.row.hasChildren">
							<el-button size="mini" type="text" icon="el-icon-plus" @click="handleAdd(scope.row)"
								v-hasPermi="['taskFilling:repair:add']">新增</el-button>
						</section>
						<section v-else>
							<el-button size="mini" type="text" icon="el-icon-s-operation"
								@click="handleChange(scope.row)"
								v-hasPermi="['taskFilling:repair:change']">换件单</el-button>
							<el-button size="mini" type="text" icon="el-icon-circle-check"
								v-if="scope.row.approvalStatus == '0' || scope.row.approvalStatus == '3'"
								@click="handleSubmit(scope.row)"
								v-hasPermi="['taskFilling:repair:submit']">提交</el-button>
							<el-button size="mini" type="text" icon="el-icon-success" @click="handleApprove(scope.row)"
								v-hasPermi="['taskFilling:repair:approve']"
								v-if="scope.row.approvalStatus == '1' && scope.row.existApprovalStatus == '0'">审批</el-button>
							<el-button size="mini" type="text" icon="el-icon-delete" @click="handleSubDelete(scope.row)"
								v-hasPermi="['taskFilling:repair:subdelete']"
								v-if="(scope.row.createTime && scope.row.approvalStatus == '3') || (scope.row.createTime && scope.row.approvalStatus == '0')">删除</el-button>
						</section>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<pagination menuNames="Pagination81" v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
			:limit.sync="queryParams.pageSize" @pagination="getList" />
		<el-dialog title="生成领料单" :visible.sync="receiveFormOpen" width="900px" append-to-body v-dialogDrag>
			<el-form ref="receiveForm" :model="receiveForm" :rules="receiveRules" label-width="140px" class="add-form1">
				<el-form-item label="外协单位" prop="outsourcedUnit">
					<el-input v-model="receiveForm.outsourcedUnit" placeholder="请输入外协单位" maxlength="20"
						show-word-limit />
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitFormReceive">确 定</el-button>
				<el-button @click="cancelReceive">取 消</el-button>
			</div>
		</el-dialog>

		<!-- 新增 -->
		<el-dialog :title="title" :visible.sync="open" width="900px" append-to-body v-dialogDrag>
			<el-form ref="form" :model="form" :rules="rules" label-width="140px" class="add-form1">
				<el-form-item label="返修任务单" prop="repairNumber">
					<el-input v-model="form.repairNumber" placeholder="请输入返修任务单" disabled />
				</el-form-item>
				<el-form-item label="工艺节点" prop="flowStatus">
					<el-select v-model="form.flowStatus" placeholder="请选择">
						<el-option v-for="dict in dict.type.flow_status" :key="dict.value" :label="dict.label"
							:value="dict.value"> </el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="产品编号" prop="productNumber">
					<el-select v-model="form.productNumber" placeholder="请选择" @change="changeProduct">
						<el-option v-for="item in productList" :key="item.productNumber" :label="item.productNumber"
							:value="item.productNumber"> </el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="产品名称" prop="productName">
					<el-input v-model="form.productName" placeholder="请输入产品名称" disabled />
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>

		<!-- 审批弹框 -->
		<el-dialog title="审批" :visible.sync="openApprove" width="900px" append-to-body v-dialogDrag>
			<ApproveTemplete @cancelApprove="cancelApprove" :openApprove="openApprove"></ApproveTemplete>
		</el-dialog>
		<!-- 审批流程弹框 -->
		<el-dialog title="审批流程" :visible.sync="openRecords" width="900px" append-to-body v-dialogDrag>
			<RecordsTemplete :approveRecord="approveRecord"></RecordsTemplete>
		</el-dialog>
	</div>
</template>

<script>
import ApproveTemplete from "@/views/components/ApproveTemplete"
import { listRepair1, approvalRecord, submitRepair, approverRepair, listRepair, listRepairChild, addRepair, getProductPlan, generateMaterial, getRepair, getProductList1, deleteRepairChild } from "@/api/taskFilling/repair"
import { mapGetters } from "vuex"
import CreateForm from "@/views/components/CreateForm"
import RecordsTemplete from "@/views/components/RecordsTemplete"
import { getcolumn } from "@/api/selectList"
import searchStateMixin from '@/layout/mixin/searchStateMixin.js'
export default {
	name: "Repair1",
	dicts: ["flow_status"],
	mixins: [searchStateMixin],
	components: { ApproveTemplete, RecordsTemplete, CreateForm },
	computed: {
		...mapGetters(["sidebar"])
	},
	data() {
		return {
			tableTreeRefreshTool: {}, // 用于存储 resolve 方法和展开状态
			approvalRequisitionStatusList: [
				{
					id: "0",
					name: "未提交"
				},
				{
					id: "1",
					name: "审批中"
				},
				{
					id: "2",
					name: "已通过"
				},
				{
					id: "3",
					name: "未通过"
				}
			],
			isMousedownTable: false, //是否按下表格
			currentEnterRow: null, //当前移入的行数据
			approveRecord: [],
			// 审批流程
			openRecords: false,
			approveRow: {},
			// 审批数据
			openApprove: false,
			eleTabTop: 0, //表格容器距浏览器顶部距离
			testval: undefined,
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 选中数组列表
			rows: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 生产计划表格数据
			RepairList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				repairNumber: undefined,
				productName: undefined,
				productModel: undefined,
				productNumber: undefined,
				approvalRequisitionStatus: undefined
			},
			// 表单参数
			form: {},
			// 表单校验
			rules: {
				productNumber: [{ required: true, message: "请选择产品编号", trigger: "blur" }],
				flowStatus: [{ required: true, message: "请选择工艺节点", trigger: "blur" }]
			},
			receiveRules: {},
			deviceList: [],
			// 修改保养计划弹框
			changeOpen: false,
			changeTitle: "",
			changeForm: {},
			ruleMonths: [],
			changeDisabled: false,
			// 更新树刷新
			treeMap: new Map(),
			isOne: true, // 是否是单条制定计划
			// 返修任务详情
			openDetail: false,
			// 生成领料单
			receiveFormOpen: false,
			receiveForm: { outsourcedUnit: "产品维修事业部" },
			// 产品列表
			productList: [],
			treetablekey: Math.random(),
			// 列信息
			columns: [
				{ key: 0, label: `返修任务单`, visible: true },
				{ key: 1, label: `产品名称`, visible: true },
				{ key: 2, label: `产品型号`, visible: true },
				{ key: 3, label: `产品编号`, visible: true },
				{ key: 4, label: `工艺流程`, visible: true },
				{ key: 5, label: `审批状态`, visible: true },
				{ key: 6, label: `生成标志`, visible: true }
			],
			pageSize: 10
		}
	},
	created() {
		// 如果是页面刷新，重置查询
		if (window.performance && performance.navigation.type === performance.navigation.TYPE_RELOAD) {
			this.resetForm("queryForm")
			// 清除URL中的查询参数（不刷新页面）
			window.history.replaceState({}, document.title, window.location.pathname);
		}
		// this.getSize()
	},
	mounted() {
		// 滚动条的获取
		this.handleScrollx()
		window.addEventListener("scroll", this.handleScrollx, true)
	},
	watch: {
		"$route.query": {
			handler(newQuery, oldQuery) {
				console.log(newQuery, "newQuery")
				if (newQuery.queryData) {
					if (Object.keys(newQuery.queryData).length === 0) {
						this.resetQuerys()
						// this.getSize()
					} else {
						this.queryParams = { ...this.queryParams, ...JSON.parse(newQuery.queryData) }
						// this.getSize()
					}
				}  this.getSize()
			},
			immediate: true, // 立即执行一次
			deep: true // 深度监听
		}
	},
	activated() {
		// this.getSize()
		//获取表格容器距页面头部的距离
		this.handleScrollx()
	},
	destroyed() {
		window.removeEventListener("scroll", this.handleScrollx, true)
	},
	methods: {
		getSize() {
			getcolumn({ pageName: "Pagination81" }).then(response => {
				this.pageSize = this.queryParams.pageSize = response.data.length ? (response.data[0].limit ? response.data[0].limit : 10) : 10
				this.getList()
			})
		},
		// 获取审批详情
		showApproveList(row) {
			if (row.approvalStatus == "0") {
				return false
			}
			this.openRecords = true
			approvalRecord({
				id: row.id.replace("c", ""),
				workflowType: "12"
			}).then(res => {
				this.openRecords = true
				this.approveRecord = res.data
			})
		},
		handleSubmits() {
			if (this.ids.length == 0) {
				this.$modal.msg("请选择产品")
				return false
			} else {
				// 判断是否选中了父级返修任务
				let checkp = this.rows.find(item => {
					return Number(item.id) > 0
				})
				if (checkp) {
					this.$modal.msg("只能选择子类产品")
					return false
				}
			}

			let ids = []
			this.ids.forEach(item => {
				ids.push(item.replace("c", ""))
			})

			this.$modal
				.confirm("是否确认提交数据项？")
				.then(() => {
					let data = {
						workIds: ids,
						workflowType: "12"
					}
					return submitRepair(data)
				})
				.then(() => {
					this.$modal.msgSuccess("操作成功")
					localStorage.setItem("todoMessage", "repair1")

					// Update only the selected rows' status without collapsing
					this.rows.forEach(row => {
						row.approvalStatus = "1" // Set to "审批中"
						row.approvalStateName = "审批中" // Update the display text if needed

						// Find the parent row to ensure it stays expanded
						const parentRow = this.RepairList.find(parent => parent.children && parent.children.some(child => child.id === row.id))

						if (parentRow && this.$refs.treetableref) {
							// Keep the parent row expanded
							this.$refs.treetableref.toggleRowExpansion(parentRow, true)
						}
					})
				})
				.catch(() => { })
		},

		handleSubmit(row) {
			this.$modal
				.confirm("是否确认提交数据项？")
				.then(function () {
					let data = {
						workId: row.id.replace("c", ""),
						workflowType: "12",
						// 1是提交，3是重复提交
						submitStatus: row.approvalStatus == "0" ? "1" : "2"
					}
					return submitRepair(data)
				})
				.then(() => {
					this.$modal.msgSuccess("操作成功")
					localStorage.setItem("todoMessage", "repairss")

					this.refreshLoadTree(row.repairId) // 刷新子级数据
				})
				.catch(() => { })
		},
		handleSubDelete(row) {
			this.$modal
				.confirm("是否确认删除数据项？")
				.then(function () {
					return deleteRepairChild(row.id.replace("c", ""))
				})
				.then(() => {
					this.refreshLoadTree(row.repairId) // 刷新子级数据

					this.$modal.msgSuccess("删除成功")
				})
				.catch(() => { })
		},
		// 审批取消/完成
		async cancelApprove(ret) {
			if (!ret.flag) {
				this.openApprove = false
				return false
			}

			try {
				let ids = []
				this.rows.forEach(item => {
					ids.push(item.id.replace("c", ""))
				})

				let data = {
					approvalStatus: ret.approvalStatus,
					causeRejection: ret.causeRejection,
					workflowType: "12"
				}

				// If approving a single row
				if (this.approveRow.id) {
					data.id = this.approveRow.id.replace("c", "")
					await approverRepair(data)
					this.$modal.msgSuccess("操作成功")
					localStorage.setItem("todoMessage", "repairss")
					this.refreshLoadTree(this.approveRow.repairId) // 刷新子级数据
				}
				// If batch approving
				else {
					data.ids = ids
					// Call API to submit approval
					await approverRepair(data)
					this.$modal.msgSuccess("操作成功")
					localStorage.setItem("todoMessage", "repairss")
					// Update UI for selected rows without collapsing
					this.rows.forEach(row => {
						// Update approval status
						row.approvalStatus = ret.approvalStatus.toString()

						// Update status display text based on approval result
						switch (ret.approvalStatus) {
							case "2":
								row.approvalStateName = "已通过"
								break
							case "3":
								row.approvalStateName = "未通过"
								break
							default:
								row.approvalStateName = "审批中"
						}

						// Ensure parent row stays expanded
						const parentRow = this.RepairList.find(parent => parent.children && parent.children.some(child => child.id === row.id))

						if (parentRow && this.$refs.treetableref) {
							this.$refs.treetableref.toggleRowExpansion(parentRow, true)
						}
					})
				}

				this.openApprove = false
				this.$refs.treetableref.clearSelection()
			} catch (error) {
				console.error("Approval error:", error)
				this.$modal.msgError("操作失败")
			}
		},
		// 审批
		handleApprove(row) {
			if (row.id) {
				this.approveRow = row
				this.openApprove = true
			} else {
				this.approveRow = {}
				let checkp = this.rows.find(item => {
					return Number(item.id) > 0
				})
				if (checkp) {
					this.$modal.msg("只能选择子类产品")
					return false
				}
				this.openApprove = true
			}
		},

		//获取表格容器距页面头部的距离
		handleScrollx() {
			this.eleTabTop = this.$refs.eleTab.getBoundingClientRect().top
		},
		refreshLoadTree(parentId) {
			console.log(parentId, "parentId")
			const { tree, treeNode, resolve } = this.treeMap.get(parentId)
			this.loadListDes(tree, treeNode, resolve) // 重新加载子级数据
			this.$refs.treetableref.clearSelection()
		},
		// 关闭所有展开的行
		closeAllExpansions() {
			this.RepairList.forEach(row => {
				this.$refs.treetableref.toggleRowExpansion(row, false)
			})
			if (this.$refs.treetableref) {
				this.$refs.treetableref.clearSelection()
			}

			this.getList()
		},
		/** 查询生产计划列表 */
		getList() {
			this.loading = true
			listRepair1(this.queryParams).then(response => {
				this.RepairList = response.rows
				this.RepairList.forEach((item, index) => {
					item.hasChildren = true
					// item.children = []
					item.sort = index + 1
				})
				this.total = response.total
				this.loading = false
			})
		},
		// 新增产品列表
		async getProductList(row) {
			let ret = await getProductList1({ repairId: row.id })
			this.productList = ret.rows
		},
		// 展开/收起时触发
		handleExpandChange(row, expanded) {
			const curr = this.tableTreeRefreshTool[row.id]
			if (!curr) return
			curr.expandCount++
			if (expanded && curr.expandCount > 1 && !curr.prevStatus) {
				listRepairChild({
					repairId: row.id,
					...this.queryParams
				}).then(res => {
					res.rows.forEach((item, index) => {
						// 父子id会冲突
						item.id = "c" + item.id
						item.sort = index + 1
					})
					curr.resolve(res.rows)
				})
			}
			curr.prevStatus = expanded
		},
		// 获取列表子菜单
		async loadListDes(tree, treeNode, resolve) {
			console.log("000")
			if (!this.treeMap.has(tree.id)) {
				this.treeMap.set(tree.id, { tree: tree, treeNode, resolve })
			}
			this.tableTreeRefreshTool[tree.id] = {
				resolve,
				expandCount: 0, // 展开次数
				prevStatus: false // 上一次的展开状态
			}
			let data = {
				repairId: tree.id,
				...this.queryParams
			}
			let ret = await listRepairChild(data)
			tree.hasChildren = ret.rows.length > 0
			tree.children = ret.rows
			if (ret.rows.length == 0) {
				resolve([])
				this.$set(this.$refs.treetableref.store.states.lazyTreeNodeMap, tree.id, [])
			} else {
				ret.rows.forEach((item, index) => {
					// 父子id会冲突
					item.id = "c" + item.id
					item.sort = index + 1
				})
				resolve(ret.rows)
				this.$set(this.$refs.treetableref.store.states.lazyTreeNodeMap, tree.id, ret.rows)
				this.$nextTick(() => {
					if (this.$refs.treetableref) {
						this.$forceUpdate()
					}
				})
			}
		},

		// 取消按钮
		cancel() {
			this.open = false
			this.reset()
		},
		// 表单重置
		reset() {
			this.form = {
				repairProductId: undefined,
				flowStatus: undefined,
				productNumber: undefined,
				productName: undefined,
				approvalRequisitionStatus: undefined
			}
			this.resetForm("form")
		},
		// 表单重置，生成领料单
		resetReceive() {
			this.receiveForm = {
				ids: undefined,
				materialNumber: undefined,
				outsourcedUnit: "产品维修事业部"
			}
			this.resetForm("receiveForm")
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1
			this.saveSearchState()
			this.closeAllExpansions()
			this.treetablekey = Math.random()
		},
		resetQuerys() {
			; (this.queryParams = {
				pageNum: 1,
				pageSize: this.pageSize,
				repairNumber: undefined,
				productName: undefined,
				productModel: undefined,
				productNumber: undefined,
				approvalRequisitionStatus: undefined
			}),
				this.resetForm("queryForm")

		},
		/** 重置按钮操作 */
		resetQuery() {
			; (this.queryParams = {
				pageNum: 1,
				pageSize: this.pageSize,
				repairNumber: undefined,
				productName: undefined,
				productModel: undefined,
				productNumber: undefined,
				approvalRequisitionStatus: undefined
			}),
				this.resetForm("queryForm")
this.clearSearchCache()
			this.handleQuery()
		},
		// 表格按下
		mousedownTable(event) {
			const target = event.target
			// 判断target的class属性确定是否点击在复选框上
			if (target.classList.contains("el-checkbox__inner")) {
				this.currentEnterRow && this.$refs.treetableref.toggleRowSelection(this.currentEnterRow)
				this.isMousedownTable = true
			}
		},
		// 单击表格行
		row_click(row, column, event) {
			// this.currentEnterRow || this.$refs.table.toggleRowSelection(row)
			if (column && column.label == "操作") {
				return
			} else {
				this.$refs.treetableref.toggleRowSelection(row)
			}
		},
		changeTableData() {
			this.$nextTick(() => {
				this.$refs.treetableref.doLayout()
			})
		},

		// 进入单元格
		cell_mouse_enter(row, column, cell, event) {
			this.isMousedownTable && this.$refs.treetableref.toggleRowSelection(row)
			this.currentEnterRow = row
		},
		// 离开单元格
		cell_mouse_leave(row, column, cell, event) {
			this.currentEnterRow = null
		},
		// 鼠标弹起或者离开表格
		mouseupTable(d) {
			this.isMousedownTable = false
		},
		// 表格每行样式
		row_class_name({ row, rowIndex }) {
			return this.rows.find(v => v.id == row.id) ? "selected" : ""
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.id)
			this.rows = selection
			this.single = selection.length !== 1
			this.multiple = !selection.length
		},
		// 新增领料单
		handleAddReceive() {
			if (this.ids.length == 0) {
				this.$modal.msg("请选择产品")
				return false
			} else {
				// 判断是否选中了父级返修任务
				let checkp = this.rows.find(item => {
					return Number(item.id) > 0
				})
				if (checkp) {
					this.$modal.msg("只能选择子类产品")
					return false
				}
			}
			this.resetReceive()
			let ids = this.ids.map(item => {
				return item.replace("c", "")
			})
			this.receiveForm.ids = ids
			this.receiveFormOpen = true
		},
		// 提交领料单
		submitFormReceive() {
			this.$refs["receiveForm"].validate(valid => {
				if (valid) {
					this.loading = true
					generateMaterial(this.receiveForm)
						.then(response => {
							this.$modal.msgSuccess("操作成功")
							this.receiveFormOpen = false
							this.rows.forEach(row => {
								row.generateFlag = "1" // Set to generated
								row.generateFlagName = "已生成" // Update display text
								const parentRow = this.RepairList.find(parent => parent.children && parent.children.some(child => child.id === row.id))

								if (parentRow && this.$refs.treetableref) {
									this.$refs.treetableref.toggleRowExpansion(parentRow, true)
								}
							})
							this.$refs.treetableref.clearSelection()
							localStorage.setItem("todoMessage", "repairTask1")
						})
						.catch(error => {
							console.error("生成领料单失败:", error)
							this.$modal.msgError("操作失败")
						})
						.finally(() => {
							this.loading = false
						})
				}
			})
		},
		// 取消弹框
		cancelReceive() {
			this.receiveFormOpen = false
			this.$refs.treetableref.clearSelection()
		},

		// 新增
		handleAdd(row) {
			this.reset()
			this.getProductList(row)
			this.open = true
			this.form.repairId = row.id
			this.form.repairNumber = row.repairNumber
			this.title = "新增"
		},
		/** 修改按钮操作 */
		handleUpdate(row) {
			this.reset()
			const id = row.id || this.ids
			getRepair(id).then(response => {
				this.form = response.data
				this.open = true
				this.title = "修改生产计划"
			})
		},
		// 更改产品
		changeProduct(e) {
			this.productList.forEach(item => {
				if (e == item.productNumber) {
					this.form.repairProductId = item.id
					this.form.productName = item.productName
				}
			})
		},
		/** 提交按钮 */
		submitForm() {
			this.$refs["form"].validate(valid => {
				if (valid) {
					addRepair(this.form).then(response => {
						this.$modal.msgSuccess("操作成功")
						this.open = false
						this.refreshLoadTree(this.form.repairId) // 刷新子级数据
					})
				}
			})
		},
		// 换件单
		handleChange(row) {
			this.$router.push({
				path: "/taskFilling/taskFill/change/index",
				query: {
					id: row.id.replace("c", ""),
					repairProductId: row.repairProductId,
					// queryParams: JSON.stringify(this.queryParams)
				}
			})
		}
	}
}
</script>
